#!/usr/local/bin/python
################################################################################
# encoder.py
#
# UTF8SMTP NIDAMail Program
# Version 1.0
# Date : July 23, 2008
# Homepage: http://sourceforge.net/projects/utf8smtp/
################################################################################

import threading, time, os
from email import base64MIME

import common

# Configuration
vh = common.vh
conf = common.conf
access = common.access

################################################################################
# Defining Functions for UTF8SMTP
# encodeMIME
################################################################################
def encodeMIME(file):

	key19 = common.makeKEY19(0)

	mail = {'FROM_CHARSET':conf['CHARSET'],
			'TO_CHARSET':conf['CHARSET'],
			'MBOX':'',
			'PRIORITY':3,
			'MAIL_FROM':'',
			'MAIL_FROM_ALT':'',
			'FROM_NAME':'',
			'FROM_EMAIL':'',
			'FROM_EMAIL_ALT':'',
			'TO':[],
			'CC':[],
			'BCC':[],
			'SUBJECT':'',
			'MAINTEXT':'',
			'ATTACH':[],
			'RFC822':[],
			'ATTACHCNT':0,
			'EACH_RCPT':0,
			'DIFFERENT_VARS':0, 
			'ERRCODE':'',
			'BOUNDARY':'----Boundary-UTF8SMTP=%s' % key19
			}

	############################################################################
	# Read header file
	############################################################################
	# /NIDAMail_Data/SEND/ing/file
	try: 
		f = open('%s/ing/%s' % (conf['ENCODE_QUEUE'], file), 'r')
	except:
		common.printLOG("encoder | Can't open %s/ing/%s" % (conf['ENCODE_QUEUE'], file), 'error')
		return -1

	try:
		for lineStr in f:
			lineStr = lineStr.strip()
			cmdStr = lineStr.upper()

			# lineStr[n:] - String except the first n characters
			if cmdStr.startswith('FROM_CHARSET='): 
				mail['FROM_CHARSET'] = lineStr[13:]
			elif cmdStr.startswith('TO_CHARSET='): 
				mail['TO_CHARSET'] = lineStr[11:]
			elif cmdStr.startswith('CHARSET='):
				mail['FROM_CHARSET'] = lineStr[8:]
				mail['TO_CHARSET'] = lineStr[8:]
			elif cmdStr.startswith('X-MBOX='): 
				mail['MBOX'] = lineStr[7:]
			elif cmdStr.startswith('X-PRIORITY='): 
				mail['PRIORITY'] = int(lineStr[11:])
			elif cmdStr.startswith('MAIL_FROM_ALT='): 
				mail['MAIL_FROM_ALT'] = lineStr[14:]
			elif cmdStr.startswith('MAIL_FROM='): 
				mail['MAIL_FROM'] = lineStr[10:]
			elif cmdStr.startswith('FROM_NAME='): 
				mail['FROM_NAME'] = lineStr[10:]
			elif cmdStr.startswith('FROM_EMAIL_ALT='): 
				mail['FROM_EMAIL_ALT'] = lineStr[15:]
			elif cmdStr.startswith('FROM_EMAIL='): 
				mail['FROM_EMAIL'] = lineStr[11:]
			elif cmdStr.startswith('TO='): 
				mail['TO'].append(lineStr[3:])
			elif cmdStr.startswith('CC='): 
				mail['CC'].append(lineStr[3:])
			elif cmdStr.startswith('BCC='): 
				mail['BCC'].append(lineStr[4:])
			elif cmdStr.startswith('SUBJECT='): 
				mail['SUBJECT'] = lineStr[8:]
			elif cmdStr.startswith('MAINTEXT='): 
				mail['MAINTEXT'] = lineStr[9:]
			elif cmdStr.startswith('ATTACH='):
				attach = lineStr[7:]
				mail['ATTACH'].append(attach)
				mail['ATTACHCNT'] += 1
			elif cmdStr.startswith('RFC822='):
				rfc822 = lineStr[7:]
				mail['RFC822'].append(rfc822)
				mail['ATTACHCNT'] += 1
			elif cmdStr.startswith('EACH_RCPT=') and lineStr[10:].strip().lower() == 'yes': 
				mail['EACH_RCPT'] = 1
			# Individual Email Send
			elif cmdStr.startswith('DIFFERENT_VARS=') and lineStr[15:].strip().lower() == 'yes': 
				mail['DIFFERENT_VARS'] = 1
			elif cmdStr.startswith('X-ERRCODE='): 
				mail['ERRCODE'] = lineStr[10:]
		f.close()

	except:
		common.printLOG("encoder | Can't read %s/ing/%s" % (conf['ENCODE_QUEUE'], file), 'error')
		return -1

	if mail['DIFFERENT_VARS'] == 1 or mail['EACH_RCPT'] == 1:
		pi = 0

		while pi < len(mail['TO']):
			eachrcpt = mail['TO'][pi]
			pi += 1
			writeMIME(mail, pi, eachrcpt)

		while pi < len(mail['TO'])+len(mail['CC']):
			eachrcpt = mail['CC'][pi-len(mail['TO'])]
			pi += 1
			writeMIME(mail, pi, eachrcpt)

		while pi < len(mail['TO'])+len(mail['CC'])+len(mail['BCC']):
			eachrcpt = mail['BCC'][pi-len(mail['TO'])-len(mail['CC'])]
			pi += 1
			writeMIME(mail, pi, eachrcpt)
	else: 
		writeMIME(mail, 0, '')

	try: 
		os.unlink('%s/ing/%s' % (conf['ENCODE_QUEUE'], file))
	except: 
		common.printLOG("encoder | Can't unlink %s/ing/%s" % (conf['ENCODE_QUEUE'], file), 'error')

	##############################################################################
	# EAI
	##############################################################################
	try: 
		os.unlink('%s/ing/%s_alt' % (conf['ENCODE_QUEUE'], file))
	except: 
		common.printLOG("encoder | Can't unlink %s/ing/%s" % (conf['ENCODE_QUEUE'], file), 'error')

	try: 
		os.unlink('%s/original/%s' % (conf['ENCODE_QUEUE'], mail['MAINTEXT']))
	except: 
		common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], mail['MAINTEXT']), 'error')

	##############################################################################
	# EAI
	##############################################################################
	try: 
		os.unlink('%s/original/%s_alt' % (conf['ENCODE_QUEUE'], mail['MAINTEXT']))
	except: 
		common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], mail['MAINTEXT']), 'error')

	for szTemp in mail['ATTACH']: 
		try: 
			os.unlink('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp))
		except: 
			common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], szTemp), 'error')

	##############################################################################
	# EAI
	##############################################################################
	for szTemp in mail['ATTACH']: 
		try: 
			os.unlink('%s/original/%s_alt' % (conf['ENCODE_QUEUE'], szTemp))
		except: 
			common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], szTemp), 'error')

	for szTemp in mail['RFC822']: 
		try: 
			os.unlink('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp))
		except: 
			common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], szTemp), 'error')

	##############################################################################
	# EAI
	##############################################################################
	for szTemp in mail['RFC822']: 
		try: 
			os.unlink('%s/original/%s_alt' % (conf['ENCODE_QUEUE'], szTemp))
		except: 
			common.printLOG("encoder | Can't unlink %s/original/%s" % (conf['ENCODE_QUEUE'], szTemp), 'error')

################################################################################
# ing : Processing currently
# before : Temporary space before processing at last -> move to parent directory
################################################################################
# writeMIME
################################################################################
def writeMIME(mail, pi, eachrcpt):

	key19 = common.makeKEY19(0)

	try: 
		f = open('%s/original/%s_original' % (conf['SEND_QUEUE'], key19), 'w')
	except:
		common.printLOG("encoder | Can't open %s/original/%s_original" % (conf['SEND_QUEUE'], key19), 'error')
		return -1
	##############################################################################
	try: 
		f_alt = open('%s/original/%s_original_alt' % (conf['SEND_QUEUE'], key19), 'w')
	except:
		common.printLOG("encoder | Can't open %s/original/%s_original_alt" % (conf['SEND_QUEUE'], key19), 'error')
		return -1
	##############################################################################

	try: 
		fh = open('%s/before/%s' % (conf['SEND_QUEUE'], key19), 'w')
	except:
		common.printLOG("encoder | Can't open %s/before/%s" % (conf['SEND_QUEUE'], key19), 'error')
		return -1

	##############################################################################
	try: 
		fh_alt = open('%s/before/%s_alt' % (conf['SEND_QUEUE'], key19), 'w')
	except:
		common.printLOG("encoder | Can't open %s/before/%s" % (conf['SEND_QUEUE'], key19), 'error')
		return -1
	##############################################################################

	try:
		fh.write('MAIL_FROM=%s\n' % (mail['MAIL_FROM']))
		fh.write('MAIL_FROM_ALT=%s\n' % (mail['MAIL_FROM_ALT']))
		###########################################################################
		print "encoder MAIL_FROM: " + str(mail['MAIL_FROM'])
		print "encoder MAIL_FROM_ALT: " + str(mail['MAIL_FROM_ALT'])
		###########################################################################
		
		fh.write('FROM=%s\n' % (mail['FROM_EMAIL']))
		fh.write('FROM_ALT=%s\n' % (mail['FROM_EMAIL_ALT']))
		###########################################################################
		print "encoder FROM: " + str(mail['FROM_EMAIL'])
		print "encoder FROM_ALT: " + str(mail['FROM_EMAIL_ALT'])
		###########################################################################

		f.write('Received: from 127.0.0.1\r\n'
				'\tby %s with %s programmed by %s\r\n'
				'\tfor <%s>; %s\r\n' % (conf['SERVER_NAME'], common.PROGRAM_NAME, common.PROGRAM_MAIL, mail['MAIL_FROM'], time.strftime('%a, %d %b %Y %X + 0900')))
		f.write('Date: %s\r\n' % (time.strftime('%a, %d %b %Y %X +0900')))
		f.write('Message-ID: <%s@%s>\r\n' % (key19, conf['SERVER_NAME']))

		if mail['FROM_NAME'] == '': 
			f.write('From: <%s <%s>>\n' % mail['FROM_EMAIL'], mail['FROM_EMAIL_ALT'])
		else: 
			f.write('From: "%s" <%s <%s>>\r\n' % (common.encodeCHARSET(mail['FROM_NAME'], mail['FROM_CHARSET'], mail['TO_CHARSET']), mail['FROM_EMAIL'], mail['FROM_EMAIL_ALT']))

		if mail['EACH_RCPT'] == 1:
			fh.write('TO=%s\n' % eachrcpt)
			f.write('To: %s\r\n' % eachrcpt)
		else:
			if mail['DIFFERENT_VARS'] == 1: fh.write('TO=%s\n' % eachrcpt)
			i = 0
			for szTemp in mail['TO']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh.write('TO=%s\n' % szTemp)
				if i == 0: 
					f.write('To: %s' % szTemp)
				else: 
					f.write(',\r\n\t%s' % szTemp)
				i += 1

			if i > 0: 
				f.write('\r\n')

			i = 0
			for szTemp in mail['CC']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh.write('TO=%s\n' % szTemp)
				if i == 0: 
					f.write('Cc: %s' % szTemp)
				else: 
					f.write(',\r\n\t%s' % szTemp)
				i += 1

			if i > 0: 
				f.write('\r\n')

			i = 0
			for szTemp in mail['BCC']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh.write('TO=%s\n' % szTemp)
				if i == 0: 
					f.write('Bcc: %s' % szTemp)
				else: 
					f.write(',\r\n\t%s' % szTemp)
				i += 1
			if i > 0: f.write('\r\n')

		f.write('Subject: %s\r\n' % common.encodeCHARSET(mail['SUBJECT'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
		f.write('X-Priority: %d\r\n' % mail['PRIORITY'])

		########################################################################
		if mail['MBOX'] != '': 
			f.write('X-MBOX: %s\r\n' % mail['MBOX'])
		########################################################################

		f.write('MIME-Version: 1.0\r\n')
		if mail['ATTACHCNT'] > 0:
			f.write('Content-Type: multipart/mixed;\r\n')
			f.write('\tboundary="%s"\r\n' % mail['BOUNDARY'])
			f.write('Content-Transfer-Encoding: base64\r\n\r\n')
			f.write('This is a multi-part message in MIME format.\r\n')
			f.write('\r\n--%s\r\n' % mail['BOUNDARY'])
	except:
		common.printLOG("encoder | Can't write %s/original/%s_original" % (conf['SEND_QUEUE'], key19), 'error')
		return -1

	##############################################################################
	# EAI
	##############################################################################
	try:
		fh_alt.write('MAIL_FROM=%s\n' % (mail['MAIL_FROM']))
		fh_alt.write('MAIL_FROM_ALT=%s\n' % (mail['MAIL_FROM_ALT']))

		fh_alt.write('FROM=%s\n' % (mail['FROM_EMAIL']))
		fh_alt.write('FROM_ALT=%s\n' % (mail['FROM_EMAIL_ALT']))

		f_alt.write('Downgraded-Mail-From: =?UTF-8?B?')
		# Display Name
		string1 = '"%s"' % (common.encodeCHARSET(mail['FROM_NAME'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
		f_alt.write(base64MIME.encode(string1, True, 76, ''))
		# Seperator
		f_alt.write('?=')
		# UTF-8 Email
		f_alt.write('=?UTF-8?B?')
		string2 = '<%s' % (common.encodeCHARSET(mail['FROM_EMAIL'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
		f_alt.write(base64MIME.encode(string2, True, 76, ''))
		# Seperator
		f_alt.write('?=')
		# ALT-Address
		f_alt.write(' <%s>>' % mail['FROM_EMAIL_ALT'])
		f_alt.write('\r\n')

		f_alt.write('Received: from 127.0.0.1\r\n'
				'\tby %s with %s programmed by %s\r\n'
				'\tfor <%s>; %s\r\n' % (conf['SERVER_NAME'], common.PROGRAM_NAME, common.PROGRAM_MAIL, mail['MAIL_FROM_ALT'], time.strftime('%a, %d %b %Y %X + 0900')))
		f_alt.write('Date: %s\r\n' % (time.strftime('%a, %d %b %Y %X +0900')))
		f_alt.write('Message-ID: <%s@%s>\r\n' % (key19, conf['SERVER_NAME']))

		if mail['FROM_NAME'] == '': 
			f_alt.write('From: <%s>\n' % mail['FROM_EMAIL_ALT'])

			# Downgrade
			f_alt.write('Downgraded-From: =?UTF-8?B?')
			string = ('<%s' % mail['FROM_EMAIL'])
			f_alt.write(base64MIME.encode(string, True, 76, ''))
			# Seperator
			f_alt.write('?=')
			f_alt.write(' <%s>>' % mail['FROM_EMAIL_ALT'])
			f_alt.write('\r\n')
		else: 
			f_alt.write('From: "%s" <%s>\r\n' % (common.encodeCHARSET(mail['FROM_NAME'], mail['FROM_CHARSET'], mail['TO_CHARSET']), mail['FROM_EMAIL_ALT']))

			# Downgrade
			f_alt.write('Downgraded-From: =?UTF-8?B?')
			# Display Name
			string1 = '"%s"' % (common.encodeCHARSET(mail['FROM_NAME'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
			f_alt.write(base64MIME.encode(string1, True, 76, ''))
			# Seperator
			f_alt.write('?=')
			# UTF-8 Email
			f_alt.write('=?UTF-8?B?')
			string2 = '<%s' % (common.encodeCHARSET(mail['FROM_EMAIL'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
			f_alt.write(base64MIME.encode(string2, True, 76, ''))
			# Seperator
			f_alt.write('?=')
			# ALT-Address
			f_alt.write(' <%s>>' % mail['FROM_EMAIL_ALT'])
			f_alt.write('\r\n')

		if mail['EACH_RCPT'] == 1:
			fh_alt.write('TO=%s\n' % eachrcpt)
			f_alt.write('To: %s\r\n' % eachrcpt)
		else:
			if mail['DIFFERENT_VARS'] == 1: 
				fh_alt.write('TO=%s\n' % eachrcpt)
			i = 0
			for szTemp in mail['TO']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh_alt.write('TO=%s\n' % szTemp)
				if i == 0: 
					f_alt.write('To: %s' % szTemp)
				else: 
					f_alt.write(',\r\n\t%s' % szTemp)
				i += 1

			if i > 0: 
				f_alt.write('\r\n')

			i = 0
			for szTemp in mail['CC']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh_alt.write('TO=%s\n' % szTemp)
				if i == 0: 
					f_alt.write('Cc: %s' % szTemp)
				else: 
					f_alt.write(',\r\n\t%s' % szTemp)
				i += 1

			if i > 0: 
				f_alt.write('\r\n')

			i = 0
			for szTemp in mail['BCC']:
				if szTemp.find('@') == -1: 
					szTemp += '@'+conf['SERVER_NAME']  
				if mail['DIFFERENT_VARS'] != 1: 
					fh_alt.write('TO=%s\n' % szTemp)
				if i == 0: 
					f_alt.write('Bcc: %s' % szTemp)
				else: 
					f_alt.write(',\r\n\t%s' % szTemp)
				i += 1
			if i > 0: 
				f_alt.write('\r\n')

		f_alt.write('Subject: %s\r\n' % common.encodeCHARSET(mail['SUBJECT'], mail['FROM_CHARSET'], mail['TO_CHARSET']))
		f_alt.write('X-Priority: %d\r\n' % mail['PRIORITY'])

		############################################################################
		if mail['MBOX'] != '': 
			f_alt.write('X-MBOX: %s\r\n' % mail['MBOX'])
		############################################################################

		f_alt.write('MIME-Version: 1.0\r\n')
		if mail['ATTACHCNT'] > 0:
			f_alt.write('Content-Type: multipart/mixed;\r\n')
			f_alt.write('\tboundary="%s"\r\n' % mail['BOUNDARY'])
			f_alt.write('Content-Transfer-Encoding: base64\r\n\r\n')
			f_alt.write('This is a multi-part message in MIME format.\r\n')
			f_alt.write('\r\n--%s\r\n' % mail['BOUNDARY'])
	except:
		common.printLOG("encoder | Can't write %s/original/%s_original" % (conf['SEND_QUEUE'], key19), 'error')
		return -1

	##############################################################################
	if os.path.exists('%s/original/%s' % (conf['ENCODE_QUEUE'], mail['MAINTEXT'])):
		try: 
			f2 = open('%s/original/%s' % (conf['ENCODE_QUEUE'], mail['MAINTEXT']), 'r')
		except:
			common.printLOG("encoder | Can't open %s/original/%s - MAINTEXT" % (conf['ENCODE_QUEUE'], mail['MAINTEXT']), 'error')
			return -1

		try:
			f.write('Content-Type: text/html; charset=%s\r\n' % mail['TO_CHARSET'])
			f.write('Content-Transfer-Encoding: base64\r\n\r\n')
			# EAI
			f_alt.write('Content-Type: text/html; charset=%s\r\n' % mail['TO_CHARSET'])
			f_alt.write('Content-Transfer-Encoding: base64\r\n\r\n')
			print "1==================================================================="
			szTemp = f2.read()
			if pi > 0: 
				szTemp = szTemp.replace('{$each}', '%07d' % pi)
			if mail['FROM_CHARSET'] != mail['TO_CHARSET']: 
				szTemp = common.decodeCHARSET(szTemp, mail['FROM_CHARSET'], mail['TO_CHARSET'], 'encoder', key19)
				print szTemp
			f.write(base64MIME.encode(szTemp, True, 76, '\r\n'))
			# EAI
			f_alt.write(base64MIME.encode(szTemp, True, 76, '\r\n'))
			f2.close()
		except:
			common.printLOG("encoder | Can't write %s/original/%s - MAINTEXT" % (conf['ENCODE_QUEUE'], mail['MAINTEXT']), 'error')
			return -1

	##############################################################################
	for szTemp in mail['ATTACH']:
		try:
			filename = szTemp[szTemp.find('_')+1:]
			if os.path.exists('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp)):
				f.write('\r\n--%s\r\n' % mail['BOUNDARY'])
				f2 = open('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp), 'rb')
				f.write('Content-Type: application/octet-stream;\r\n')
				f.write('\tname="%s"\r\n' % common.encodeCHARSET(filename, mail['FROM_CHARSET'], mail['TO_CHARSET']))
				f.write('Content-Transfer-Encoding: base64\r\n')
				f.write('Content-Disposition: attachment;\r\n')
				f.write('\tfilename="%s"\r\n\r\n' % common.encodeCHARSET(filename, mail['FROM_CHARSET'], mail['TO_CHARSET']))
				f.write(base64MIME.encode(f2.read(), True, 76, '\r\n'))
				f2.close()
		except:
			common.printLOG("encoder | Can't write %s/original/%s - ATTACH" % (conf['ENCODE_QUEUE'], szTemp), 'error')
			return -1

	##############################################################################
	# EAI	
	##############################################################################
	for szTemp in mail['ATTACH']:
		try:
			filename = szTemp[szTemp.find('_')+1:]

			if os.path.exists('%s/original/%s_alt' % (conf['ENCODE_QUEUE'], szTemp)):
				f_alt.write('\r\n--%s\r\n' % mail['BOUNDARY'])
				f3 = open('%s/original/%s_alt' % (conf['ENCODE_QUEUE'], szTemp), 'rb')
				f_alt.write('Content-Type: application/octet-stream;\r\n')
				f_alt.write('\tname="%s"\r\n' % common.encodeCHARSET(filename, mail['FROM_CHARSET'], mail['TO_CHARSET']))
				f_alt.write('Content-Transfer-Encoding: base64\r\n')
				f_alt.write('Content-Disposition: attachment;\r\n')
				f_alt.write('\tfilename="%s"\r\n\r\n' % common.encodeCHARSET(filename, mail['FROM_CHARSET'], mail['TO_CHARSET']))
				f_alt.write(base64MIME.encode(f3.read(), True, 76, '\r\n'))
				f3.close()
		except:
			common.printLOG("encoder | Can't write %s/original/%s - ATTACH" % (conf['ENCODE_QUEUE'], szTemp), 'error')
			return -1

	##############################################################################
	for szTemp in mail['RFC822']:
		try:
			if os.path.exists('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp)):
				f.write('\r\n--%s\r\n' % mail['BOUNDARY'])
				# EAI
				f_alt.write('\r\n--%s\r\n' % mail['BOUNDARY'])
				f2 = open('%s/original/%s' % (conf['ENCODE_QUEUE'], szTemp), 'r')
				f.write('Content-Type: message/rfc822\r\n\r\n')
				f.write(f2.read())
				# EAI
				f_alt.write('Content-Type: message/rfc822\r\n\r\n')
				f_alt.write(f2.read())
				f2.close()
		except:
			common.printLOG("encoder | Can't write %s/original/%s - RFC822" % (conf['ENCODE_QUEUE'], szTemp), 'error')
			return -1

	##############################################################################
	try:
		if mail['ATTACHCNT'] > 0: 
			f.write('\r\n\r\n--%s--\r\n' % mail['BOUNDARY'])
			# EAI
			f_alt.write('\r\n\r\n--%s--\r\n' % mail['BOUNDARY'])
		f.close()
		fh.close()
	except:
		common.printLOG("encoder | Can't write %s/original/%s_original" % (conf['SEND_QUEUE'], key19), 'error')
		return -1

	##############################################################################
	try: 
		os.rename('%s/before/%s' % (conf['SEND_QUEUE'], key19), '%s/%s' % (conf['SEND_QUEUE'], key19))
	except: 
		common.printLOG("encoder | Can't rename %s/before/%s to %s/%s" % (conf['SEND_QUEUE'], key19, conf['SEND_QUEUE'], key19), 'error')
		return -1

	#############################################################################
	# EAI	
	#############################################################################
	try:
		os.rename('%s/before/%s_alt' % (conf['SEND_QUEUE'], key19), '%s/%s_alt' % (conf['SEND_QUEUE'], key19))
	except: 
		print "333333333333333333333333333333333333333333333333333333333333333333333" 
		common.printLOG("encoder | Can't rename %s/before/%s to %s/%s" % (conf['SEND_QUEUE'], key19, conf['SEND_QUEUE'], key19), 'error')
		return -1

################################################################################
# MAIN
################################################################################
common.setUIDGID('encoder')
common.printLOG('encoder | ENCODER is started', 'common')

# /NIDAMail_Data/ENCODING/before
list = os.listdir('%s/before' % conf['ENCODE_QUEUE'])

for file in list:
	# Remove all files in /NIDAMail_Data/ENCODING/before
	try: 
		os.unlink('%s/before/%s' % (conf['ENCODE_QUEUE'], file))
	except: 
		common.printLOG("ENCODER  | Can't unlink %s/before/%s" % (conf['ENCODE_QUEUE'], file), 'error')

# /NIDAMail_Data/ENCODING/ing
list = os.listdir('%s/ing' % (conf['ENCODE_QUEUE']))

for file in list:
	# /NIDAMail_Data/ENCODING/ing/file -> /NIDAMail_Data/ENCODING/file
	try: 
		os.rename('%s/ing/%s' % (conf['ENCODE_QUEUE'], file), '%s/%s' % (conf['ENCODE_QUEUE'], file))
	except: 
		common.printLOG("encoder | Can't rename %s/ing/%s to %s/%s" % (conf['ENCODE_QUEUE'], file, conf['ENCODE_QUEUE'], file), 'error')

while 1:
	common.loadVH('encoder')
	common.loadConf('encoder')
	common.loadAccess('encoder')

	# /NIDAMail_Data/ENCODING/
	list = os.listdir(conf['ENCODE_QUEUE'])
	# list[] = ['original', 'ing', 'before']

	for file in list:
		# Subscripted (The first 14 characters)
		# YYYYMMDDHHMMSS
		intNow = int(common.makeKEY19(0)[0:14])

		# If there are files in addition to ing, before, original directories
		if not file in ('ing', 'before', 'original'):
			if int(file[0:14]) > intNow: 
				continue
			# /NIDAMail_Data/ENCODING/file -> /NIDAMail_Data/ENCODING/ing/file
			try: 
				os.rename('%s/%s' % (conf['ENCODE_QUEUE'], file), '%s/ing/%s' % (conf['ENCODE_QUEUE'], file))
			except: 
				common.printLOG("encoder | Can't rename %s/%s to %s/ing/%s" % (conf['ENCODE_QUEUE'], file, conf['ENCODE_QUEUE'], file), 'error')
			else:
				common.printLOG(file, 'encoder')
				if conf['ENCODER_TYPE'] == 'fork':
					pid = os.fork()
					if pid == 0:
						encodeMIME(file)
						os.sys.exit(0)
					th = threading.Thread(target=common.waitPID, args=())
					th.start()
					while(threading.activeCount() > conf['ENCODER_MAX_THREADS']):
						common.printLOG('encoder | fork count is larger than %s' % conf['ENCODER_MAX_THREADS'], 'error')
						time.sleep(1)
				elif conf['ENCODER_TYPE'] == 'threading':
					th = threading.Thread(target=encodeMIME, args=(file, ))
					th.start()
					while(threading.activeCount() > conf['ENCODER_MAX_THREADS']):
						common.printLOG('encoder | thread count is larger than %s' % (conf['ENCODER_MAX_THREADS']), 'error')
						time.sleep(1)
				else: 
					encodeMIME(file)

	time.sleep(1)
################################################################################
# End of file	
################################################################################
